/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.diplomka.servicelayer.gamelogic.resolver;

import cz.muni.fi.diplomka.servicelayer.dto.IncomingResources;
import cz.muni.fi.diplomka.servicelayer.dto.Message;
import cz.muni.fi.diplomka.servicelayer.gamelogic.manager.CityManager;
import cz.muni.fi.diplomka.servicelayer.gamelogic.manager.CityResourcesManager;
import cz.muni.fi.diplomka.servicelayer.gamelogic.manager.MarketManager;
import cz.muni.fi.diplomka.servicelayer.gamelogic.manager.MessageManager;
import cz.muni.fi.diplomka.servicelayer.gamelogic.managerimpl.CityManagerImpl;
import cz.muni.fi.diplomka.servicelayer.gamelogic.managerimpl.CityResourcesManagerImpl;
import cz.muni.fi.diplomka.servicelayer.gamelogic.managerimpl.MarketManagerImpl;
import cz.muni.fi.diplomka.servicelayer.gamelogic.managerimpl.MessageManagerImpl;
import java.sql.Timestamp;

/**
 * Class used for checking if Resources has arrived to City
 *
 * @author Jakub Kutil
 */
public class IncomingResourcesResolver {

    private static CityResourcesManager cityResourcesManager = new CityResourcesManagerImpl();
    private static CityManager cityManager = new CityManagerImpl();
    private static MarketManager marketManager = new MarketManagerImpl();
    private static MessageManager messageManager = new MessageManagerImpl();

    public static void main(String[] args) throws InterruptedException {
        while (true) {
            for (IncomingResources incomingResources : marketManager.getAllIncomingResources()) {
                Timestamp now = new Timestamp(System.currentTimeMillis());
                if (incomingResources.getTimeOfArrival().before(now)) {
                    cityResourcesManager.increaseResource(incomingResources.getCityTo(), incomingResources.getResource(), incomingResources.getResourceCount());
                    marketManager.deleteIncomingResources(incomingResources.getId());

                    Message message = new Message();
                    message.setIdFrom(new Long(1));
                    message.setIdTo(cityManager.getOwnerOfCity(incomingResources.getCityTo()).getId());
                    message.setSubject("Caravan has arrived");
                    message.setBody("Your city " + cityManager.getCityById(incomingResources.getCityTo()).getName()
                            + " recieved " + incomingResources.getResourceCount() + " "
                            + incomingResources.getResource() + " from " + cityManager.getCityById(incomingResources.getCityFrom()).getName() + ".");
                    message.setTime(now);
                    message.setUnread(true);

                    messageManager.addMessage(message);
                }
            }
            Thread.sleep(1000);
        }
    }
}
